# -*- coding: utf-8 -*-
import urllib2



def main(name1):
    name1 = name1.decode('utf-8')
    #name1 = name1.decode('utf-8')
    #name1 = u"凡人修仙传"
    #print name1, type(name1)
    name = name1.encode('utf-8')
    name = urllib2.quote(name)

    url = "http://www.yhdm.io/search/%s/" % name
    print "search url:", url
    data = urllib2.urlopen(url).read()

    import bs4

    soup = bs4.BeautifulSoup(data,'html5lib')
    harf = soup.select('.lpic')[0].select('ul')[0].select('li')[0].select('a')[0].get('href')

    url = 'http://www.yhdm.io%s' % harf

    print "main url:", url

    data = urllib2.urlopen(url).read()
    soup = bs4.BeautifulSoup(data,'html5lib')


    urls = []
    for li in soup.select('.movurl')[0].select('ul')[0].select('li'):
        harf = li.select('a')[0].get('href')
        url = 'http://www.yhdm.io%s' % harf
        data = urllib2.urlopen(url).read()
        soup = bs4.BeautifulSoup(data,'html5lib')

        urls.append((li.getText(), soup.select('.bofang')[0].select("#playbox")[0].get('data-vid').split("$")[0]))

        print soup.select('.bofang')[0].select("#playbox")[0].get('data-vid').split("$")[0]


    with open(u"%s.m3u" % name1, "w") as f:
        f.write("#EXTM3U\n")
        for url in urls:
            f.write("#EXTINF:-1," + 'group-title="%s", ' % name1.encode("utf-8")  + name1.encode("utf-8") + url[0].encode('utf-8') + "\n")
            f.write(url[1] + "\n")


if __name__ == "__main__":
    import sys
    main(sys.argv[1])
    
